import 'package:cher_flare/modules/discovery/ly_discovery_page.dart';
import 'package:cher_flare/modules/home_page/views/ly_congratulations_page.dart';
import 'package:cher_flare/modules/login/models/ly_login_info_manager.dart';
import 'package:cher_flare/modules/video/controllers/ly_video_home_controller.dart';
import 'package:cher_flare/personal_center/controllers/ly_personal_center_controller.dart';
import 'package:cher_flare/routes/app_pages.dart';
import 'package:cher_flare/utils/app_color.dart';
import 'package:cher_flare/utils/ly_medal_manager.dart';
import 'package:cher_flare/utils/ly_use_log_manager.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../../config/config.dart';
import '../../../config/url_api.dart';
import '../../../http/http_utils.dart';
import '../../../personal_center/views/ly_personal_center_page.dart';
import '../../discovery/controllers/ly_works_list_controller.dart';
import '../../video/views/ly_video_home_page.dart';
import 'home_content_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  late TabController tabController;
  int _currentSelectedIndex = 0;
  @override
  void initState() {
    super.initState();
    tabController = TabController(length: 4, vsync: this);
    _checkToken();
    _requestConfig();
  }

  void _didClickItem(int index) {
    if (_currentSelectedIndex == index) {
      return;
    }
    _currentSelectedIndex = index;
    if (index != 2) {
      final controller = Get.find<LYVideoHomeController>();
      if (controller.initialized) {
        controller.stopPlay();
      }
      if (index == 1) {
        final worksController = Get.find<LYWorksListController>();
        if (worksController.initialized) {
          worksController.refreshWorksData();
        }
      } else if (index == 3) {
        final personalController = Get.find<LYPersonalCenterController>();
        if (personalController.initialized) {
          personalController.refreshUserInfo();
          personalController.refreshWorks();
        }
      }
    } else {
      final controller = Get.find<LYVideoHomeController>();
      if (controller.initialized) {
        controller.loadVideos();
        controller.startPlay();
      }
    }
    setState(() {});
  }

  void _checkToken() async {
    EasyLoading.show();
    Map<String, dynamic> parameters = {
      'token': LYLoginInfoManager.getInstance.loginModel?.token
    };
    final res = await HttpUtils.getInstance.post(
      URLApi.validToken,
      data: parameters,
    );
    EasyLoading.dismiss();
    if (!res.isSuccess) {
      Get.offAndToNamed(AppPages.login);
    }
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: IndexedStack(
            sizing: StackFit.expand,
            index: _currentSelectedIndex,
            children: const [
              HomeContentPage(),
              LYDiscoveryPage(),
              LYVideoHomePage(),
              LYPersonalCenterPage(),
            ],
          ),
        ),
        Container(
          color: AppColors.whiteColor,
          child: SafeArea(
            top: false,
            child: Container(
              height: 49,
              decoration: const BoxDecoration(
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(24),
                    topRight: Radius.circular(24)),
                color: AppColors.whiteColor,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  _makeTabItem(0),
                  _makeTabItem(1),
                  _makeTabItem(2),
                  _makeTabItem(3),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _makeTabItem(int index) {
    return Expanded(
      child: InkWell(
        onTap: () => _didClickItem(index),
        child: Container(
          alignment: Alignment.center,
          height: 49,
          child: index == _currentSelectedIndex
              ? Image.asset(
                  'assets/images/tab_${index}_h.png',
                  width: 24,
                  height: 24,
                )
              : Image.asset('assets/images/tab_${index}_n.png',
                  width: 24, height: 24),
        ),
      ),
    );
  }

  void _requestConfig() async {
    EasyLoading.show();
    final res = await HttpUtils.getInstance
        .get(URLApi.appConfig, queryParameters: {'ver': 0});
    final data = res.data;
    if (data is Map) {
      final items = data['items'];
      if (items is List) {
        for (final item in items) {
          if (item['name'] == 'rck') {
            Config.rck = item['data'];
          } else if (item['name'] == 'google_translation_key') {
            Config.googleTranslationKey = item['data'];
          }
        }
      }
    }
    EasyLoading.dismiss();
  }
}
